package com.llap.exp190929.service;

import com.llap.exp190929.entity.Category;
import com.llap.exp190929.repository.CategoryRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class CategoryService {
    private CategoryRepository categoryRepository;

    public Category findCategory(int id) {
        return categoryRepository.findById(id).orElse(null);
    }

    public Page<Category> findCategories(int page, int pageSize) {
        return categoryRepository.findAll(PageRequest.of(page - 1, pageSize));
    }

    @Transactional
    public Category addCategory(Category documentcategory) {
        if (documentcategory.getId() != null) return null;
        return categoryRepository.save(documentcategory);
    }

    @Transactional
    public Category updateCategory(Category documentcategory) {
        if (documentcategory.getId() == null) return null;
        return categoryRepository.save(documentcategory);
    }

    @Transactional
    public void deleteCategory(int id) {
        categoryRepository.deleteById(id);
    }
}
